package com.example.xutilsdowndemo;

import java.io.File;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class DownloadService extends Service
{
	public static String APP_NAME = "App_Name";
	public static String URL = "Url";
	public static String DRAWABLEID = "DrawableId";

	private String path = Environment.getExternalStorageDirectory() + "/";
	private String Url;
	private HttpUtils http;
	private HttpHandler handler;
	private String app_name;
	private int drawableid;

	private NotificationManager notificationManager;
	private Notification notification;
	private Intent updateIntent;
	private PendingIntent pendingIntent;
	private RemoteViews contentView;
	private String filepath;
	private Boolean isdownload = false;
    private NotificationBroadcastReceiver notificationbroadcastreceiver;
	class NotificationBroadcastReceiver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			Log.i("====", isdownload + "");
			if (isdownload)
			{
				handler.cancel();
				isdownload = false;
				notification.contentView.setTextViewText(
						R.id.download_notificationTitle, "暂停下载，点击继续");
				notificationManager.notify(
						R.layout.download_notification_layout, notification);
			} else
			{
				handler = http.download(Url, filepath, true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
						true, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
						mRequestCallBack);
			}
		}

	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public void onCreate()
	{

		super.onCreate();
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		IntentFilter intentpause = new IntentFilter();
		intentpause.addAction("com.woodnaonly.DownloadService");
		notificationbroadcastreceiver = new NotificationBroadcastReceiver();
		this.registerReceiver(pausenotificationbroadcastreceiver, intentpause);

	}
        @Override
	public void onDestroy()
	{
		unregisterReceiver(notificationbroadcastreceiver);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{

		
		app_name = intent.getStringExtra(APP_NAME);
		Url = intent.getStringExtra(URL);
		//传入下载图标，如果为空则为应用图标
		drawableid = intent.getIntExtra(DRAWABLEID, getApplicationInfo().icon);
		filepath = path + app_name + ".apk";

		Log.i("====", app_name);
		Log.i("====", Url);
		Log.i("====", drawableid + "");
		Log.i("====", filepath);
		http = new HttpUtils();
		handler = http.download(Url, filepath, true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
				true, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
				mRequestCallBack);

		return super.onStartCommand(intent, flags, startId);
	}

	// 安装apk
	private void installApk(File file)
	{
		Uri uri = Uri.fromFile(file);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		/********** 加这个属性是因为使用Context的startActivity方法的话，就需要开启一个新的task **********/
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
		stopSelf();// 自杀
	}

	// 创建通知栏
	private void createNotification()
	{
		notification = new Notification(drawableid, "正在下载",
				System.currentTimeMillis());
		notification.flags=Notification.FLAG_ONGOING_EVENT;
		contentView = new RemoteViews(getPackageName(),
				R.layout.download_notification_layout);
		contentView.setTextViewText(R.id.download_notificationTitle, "正在下载");
		contentView.setTextViewText(R.id.download_notificationPercent, "0%");
		contentView.setProgressBar(R.id.download_notificationProgress, 100, 0,
				false);
		notification.contentView = contentView;
		notificationManager.notify(R.layout.download_notification_layout,
				notification);
	}

	// 更新通知栏
	private void updatenotification(long total, long current)
	{
		int percentage = (int) (current / (total * 1.0) * 100);// 百分比
		contentView.setTextViewText(R.id.download_notificationPercent,
				percentage + "%");
		contentView.setProgressBar(R.id.download_notificationProgress, 100,
				percentage, false);
		Intent intent = new Intent("com.woodnaonly.DownloadService");
		pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
		notification.contentIntent = pendingIntent;
		notification.contentView = contentView;
		notificationManager.notify(R.layout.download_notification_layout,
				notification);
	}

	// 点击通知栏安装
	private void clicknotificationinstallapk(File file)
	{
		Uri uri = Uri.fromFile(file);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		notification.setLatestEventInfo(this, app_name, "下载完成", pendingIntent);
		notificationManager.notify(R.layout.download_notification_layout,
				notification);
	}

	RequestCallBack<File> mRequestCallBack = new RequestCallBack<File>()

	{

		@Override
		public void onStart()
		{
			createNotification();
			isdownload = true;
		}

		@Override
		public void onLoading(long total, long current, boolean isUploading)
		{
			updatenotification(total, current);
		}

		@Override
		public void onSuccess(ResponseInfo<File> responseInfo)
		{
			notificationManager.cancelAll();
			installApk(new File(filepath));
		}

		@Override
		public void onFailure(HttpException error, String msg)
		{
			Log.i("=======", "onFailure:" + msg);
			// 如果下载完成则取消通知栏
			if (msg.equals("maybe the file has downloaded completely"))
			{
				notificationManager.cancelAll();
				installApk(new File(filepath));
			}

		}
	};

}